﻿using B.S.BasicData.Api.Read.Application.Command.Account;
using B.S.BasicData.Api.Read.Dtos;
using B.S.BasicData.Domain.Entities;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interfaces;
using B.S.BasicData.Infrastructure.Utils;
using Consul;
using MD5Hash;
using MediatR;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Text;
using System.Transactions;
using Yitter.IdGenerator;

namespace B.S.BasicData.Api.Read.Application.CommandHandler.Account
{

    /// <summary>
    /// 中介者登录处理类
    /// </summary>
    public class LoginAccountHandler : IRequestHandler<LoginAccountCommand, ApiResult<int>>
    {
        private readonly ILogger<LoginAccountHandler> logger;//日志
        private readonly IBaseRepository<AccountModel> accRepo;//仓储
        private readonly IBaseRepository<LogModel> logRepo;

        public LoginAccountHandler(ILogger<LoginAccountHandler> logger,
            IBaseRepository<AccountModel> accRepo,
            IBaseRepository<LogModel> logRepo
            )
        {
            this.logger = logger;
            this.accRepo = accRepo;
            this.logRepo = logRepo;
        }
        /// <summary>
        /// 登录的处理方法
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<ApiResult<int>> Handle(LoginAccountCommand request, CancellationToken cancellationToken)
        {
            using (TransactionScope tran = new TransactionScope())


            {
                try
                {
                    logger.LogInformation($"用户{request.AccountName}正在登录");

                    ApiResult<int> result = new ApiResult<int>();//定义响应包装类 apiresult

                    //根据用户名查询要登陆的用户
                    var account = accRepo.Query().Result.Where(x => x.AccountName == request.AccountName).FirstOrDefault();




                    if (account == null)
                    {//用户不存在
                        result.Code = ApiEnums.LoginUserNotExisit;
                        result.Msg = ApiEnums.LoginUserNotExisit.Descrption();
                        result.Data = 0;
                        logger.LogInformation($"用户{request.AccountName}不存在!");
                       
                    }
                    else
                    {

                        if (account.AccountPass != request.AccountPass)
                        {
                            result.Code = ApiEnums.LoginPasswordError;
                            result.Msg = ApiEnums.LoginPasswordError.Descrption();
                            result.Data = -1;
                            logger.LogInformation($"用户{request.AccountName}密码不正确!");
                            logRepo.CreateAsync(new LogModel()
                            {
                                Id = YitIdHelper.NextId(),
                                CreateName = account.AccountName,
                                LogContent = "密码不正确",
                                CreatTime = DateTime.Now,

                            });
                        }
                        else
                        {
                            result.Code = ApiEnums.LoginOk;
                            result.Msg = ApiEnums.LoginOk.Descrption()+ "Bearer "+CreateTokenString();

                            result.Data = 1;
                        
                            //记录日志
                            logRepo.CreateAsync(new LogModel()
                            {
                                Id = YitIdHelper.NextId(),
                                CreateName = account.AccountName,
                                LogContent = "登录成功",
                                CreatTime = DateTime.Now,
                                 

                            });
                          

                            logger.LogInformation($"用户{request.AccountName}登录成功!");

                      

                        }
                    }
                    return Task.FromResult(result);

                }
                catch (Exception e)
                {

                    logger.LogError("登录失败=>" + e.Message);
                    throw;
                }
            }
        }
        /// <summary>
        /// 生成 JWT Token（令牌）
        /// </summary>
        /// <returns></returns>
        private string CreateTokenString()
        {
            //私钥
            var secretByte = Encoding.UTF8.GetBytes("kdsfldsflkdslkflkdsflkdslfdslkflk");
            // 非对称加密
            var signingKey = new SymmetricSecurityKey(secretByte);
            // 使用256 生成数字签名
            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
            // 生成Token
            var token = new JwtSecurityToken(
                issuer: "BeiJingBW",
                audience: "BeiJingBW",
                expires: DateTime.Now.AddDays(1), // 一天后过期
                signingCredentials: signingCredentials
            );
            // 生成token 字符串
            var strToken = new JwtSecurityTokenHandler().WriteToken(token);
            return strToken;
        }
    }
}
           
    

